package com.zidian.teacher.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.teacher.R;
import com.zidian.teacher.adapter.AttendanceStudentAdapter;
import com.zidian.teacher.bean.AttendanceStudentBean;
import com.zidian.teacher.bean.ClassListBean;
import com.zidian.teacher.bean.StudentAttendanceBean;
import com.zidian.teacher.common.Constant;
import com.zidian.teacher.common.ToolBarActivity;
import com.zidian.teacher.utils.GetUserInfo;
import com.zidian.teacher.utils.ProgressBarBlackUtil;
import com.zidian.teacher.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/9/12 0012.
 * <p>
 * 课堂考勤 以班级为单位  对班级学生进行考勤
 */
public class AttendanceActivity extends ToolBarActivity implements View.OnClickListener {


    @Bind(R.id.total_class_spinner)
    Spinner totalClassSpinner;
    @Bind(R.id.list)
    RecyclerView mRecyclerView;
    @Bind(R.id.label_late)
    TextView labelLate;
    @Bind(R.id.label_early)
    TextView labelEarly;
    @Bind(R.id.label_absenteeism)
    TextView labelAbsenteeism;
    @Bind(R.id.label_leave)
    TextView labelLeave;
    @Bind(R.id.sumbit)
    TextView sumbit;
    private List<String> data_list = new ArrayList<>();
    private List<AttendanceStudentBean> data = new ArrayList<>();
    private AttendanceStudentAdapter adapter;
    private ArrayAdapter<String> arr_adapter;
    private String courseId;
    private String courseWeeklyId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_left);
        setContentView(R.layout.activity_attendance);
        setTitle("考勤");
        ButterKnife.bind(this);
        courseId = getIntent().getStringExtra("courseId");
        courseWeeklyId = getIntent().getStringExtra("courseWeeklyId");
        initView();
        getClassList();
    }

    /**
     * 初始化
     */
    private void initView() {
        adapter = new AttendanceStudentAdapter(context, data);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);

        //添加点击事件
        adapter.setOnItemClickListener(new AttendanceStudentAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                for (int i = 0; i < data.size(); i++) {
                    if (i == position) {
                        data.get(i).setIsSelect(true);
                    } else {
                        data.get(i).setIsSelect(false);
                    }
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

        labelEarly.setOnClickListener(this);
        labelAbsenteeism.setOnClickListener(this);
        labelLate.setOnClickListener(this);
        labelLeave.setOnClickListener(this);
        sumbit.setOnClickListener(this);

        totalClassSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                data.clear();
                //选择班级，获取学生
                getStudent(data_list.get(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


    }


    /**
     * 从后台获取到考勤的班级列表 同时通过班级去获取学生
     */
    private void getClassList() {
        String loginUrl = Constant.URL_GOAL + "attendance/selectClass";
        HashMap<String, String> map = new HashMap<>();
        map.put("courseId", courseId);
        map.put("teacherId", GetUserInfo.getTeacherId(context));
        map.put("token", GetUserInfo.getToken(context));
        ProgressBarBlackUtil.loadShow(this);
        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.showToast(context, e.getMessage());
                ProgressBarBlackUtil.loadCancel();
            }

            @Override
            public void onResponse(String response, int id) {
                ProgressBarBlackUtil.loadCancel();
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {

                        ToastUtil.showToast(context, jsonObject.getString("message"));
                        return;
                    } else {
//                        ToastUtil.showToast(context, "成功！");
                    }

                } catch (JSONException e) {

                }

                Gson gson = new Gson();
                ClassListBean model = gson.fromJson(response, ClassListBean.class);
                if (model.isSuccess()) {

                    //数据
                    data_list = new ArrayList<>();

                    for (int i = 0; i < model.getData().size(); i++) {
                        data_list.add(model.getData().get(i).getClassId());
                    }

                    //适配器
                    arr_adapter = new ArrayAdapter<>(context, R.layout.spinner_item, data_list);
                    //设置样式
                    arr_adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
                    //加载适配器
                    totalClassSpinner.setAdapter(arr_adapter);

//                    getDate(model);
//                    getStudent(data_list.get(0));

                }

            }
        });
    }

    /**
     * @param model 获取到的学生信息 展示和渲染到页面
     */
    private void getDate(StudentAttendanceBean model) {
        data.clear();
        for (int i = 0; i < model.getData().size(); i++) {
            data.add(new AttendanceStudentBean(model.getData().get(i).getStudentHeadPortrait(), model.getData().get(i).getStudentName(), model.getData().get(i).getStudentId(), false, model.getData().get(i).getAttendance()));
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.label_late:
                setAttendance(1);
                break;
            case R.id.label_early:
                setAttendance(2);
                break;
            case R.id.label_absenteeism:
                setAttendance(3);
                break;
            case R.id.label_leave:
                setAttendance(4);
                break;
            case R.id.sumbit:
                updataAttendance();
                break;
        }
    }

    /**
     * @param code 通过考勤的按钮 对学生进行考勤标记
     */
    private void setAttendance(int code) {
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).isSelect()) {
                data.get(i).setCode(code + "");
            }
        }
        adapter.notifyDataSetChanged();


    }

    /**
     * @param className 通过后台根据班级获取学生
     */
    private void getStudent(String className) {

        String loginUrl = Constant.URL_GOAL + "attendance/select";
        HashMap<String, String> map = new HashMap<>();
        map.put("courseId", courseId);
        map.put("courseWeeklyId", courseWeeklyId);
        map.put("teacherId", GetUserInfo.getTeacherId(context));
        map.put("className", className);
        map.put("token", GetUserInfo.getToken(context));

        ProgressBarBlackUtil.loadShow(this);
        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ProgressBarBlackUtil.loadCancel();
                ToastUtil.showToast(context, "获取列表失败！");
            }

            @Override
            public void onResponse(String response, int id) {
                ProgressBarBlackUtil.loadCancel();
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(context, jsonObject.getString("message"));
                        adapter.notifyDataSetChanged();
                        return;
                    } else {
//                        ToastUtil.showToast(context, "成功！");
                    }

                } catch (JSONException e) {

                }

                Gson gson = new Gson();
                StudentAttendanceBean model = gson.fromJson(response, StudentAttendanceBean.class);
                if (model.isSuccess()) {
                    getDate(model);
                }

            }
        });
    }


    /**
     * 提交考勤的信息  一次性提交
     */
    private void updataAttendance() {

        String loginUrl = Constant.URL_GOAL + "attendance/add";
        String jsonresult = "";//定义返回字符串
        try {
            JSONArray jsonarray = new JSONArray();
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObjAnswer = new JSONObject();//pet对象，json形式
                jsonObjAnswer.put("studentId", data.get(i).getStudyID());
                jsonObjAnswer.put("attendanceContent", data.get(i).getCode());
                jsonarray.put(jsonObjAnswer);
            }
            jsonresult = jsonarray.toString();//生成返回字符串
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("student", jsonresult);
        map.put("courseId", courseId);
        map.put("courseWeeklyId", courseWeeklyId);
        map.put("teacherId", GetUserInfo.getTeacherId(context));
        map.put("token", GetUserInfo.getToken(context));

        ProgressBarBlackUtil.loadShow(this);
        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("E", e.toString());
                ToastUtil.showToast(context, e.getMessage());
                ProgressBarBlackUtil.loadCancel();
            }

            @Override
            public void onResponse(String response, int id) {
                ProgressBarBlackUtil.loadCancel();
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(context, jsonObject.getString("message"));
                        return;
                    } else {
                        ToastUtil.showToast(context, "成功！");
                        finish();
                    }

                } catch (JSONException e) {

                }


            }
        });
    }


}
